﻿// -----------------------------------------------------------------------
// <copyright file="ProjectSigningManager.cs" company="Adam Toth">
// Copyright © Adam Toth 2013
// </copyright>
// -----------------------------------------------------------------------
namespace ServiceAppStarterKit.TemplateWizard
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using EnvDTE;

    /// <summary>
    /// Class to generate key file and configure a project for strong name signing.
    /// </summary>
    public class ProjectSigningManager
    {
        /// <summary>
        /// The key file name.
        /// </summary>
        private const string KeyFileName = "key.snk";

        /// <summary>
        /// Buffer to hold the key file contents.
        /// </summary>
        private byte[] keyBuffer;

        /// <summary>
        /// Boolean indicating success.
        /// </summary>
        private bool strongNameGenerated = false;

        #region Methods used by the project wizard

        /// <summary>
        /// Generates the key file data.
        /// </summary>
        internal void GenerateKeyFile()
        {
            if (!this.strongNameGenerated)
            {
                this.keyBuffer = CreateNewKeyPair();
                this.strongNameGenerated = true;
            }
        }

        /// <summary>
        /// Adds a key file to a project.
        /// </summary>
        /// <param name="project">The project to configure.</param>
        internal void AddKeyFile(Project project)
        {
            if (this.strongNameGenerated)
            {
                this.AddKeyFileToProject(project);
            }
        }

        #endregion

        #region Private members

        /// <summary>
        /// Creates the new key pair.
        /// </summary>
        /// <returns>A byte array.</returns>
        private static byte[] CreateNewKeyPair()
        {
            IntPtr buffer = IntPtr.Zero;
            uint bufferSize;
            byte[] keyFileBuffer;

            try
            {
                if (0 == NativeMethods.StrongNameKeyGen(IntPtr.Zero, 0, out buffer, out bufferSize))
                {
                    Marshal.ThrowExceptionForHR(NativeMethods.StrongNameErrorInfo());
                }

                if (buffer == IntPtr.Zero)
                {
                    throw new InvalidOperationException("Cannot generate the strong name key.");
                }

                // Copy generated key to managed memory.
                keyFileBuffer = new byte[bufferSize];
                Marshal.Copy(buffer, keyFileBuffer, 0, (int)bufferSize);
            }
            finally
            {
                // Free native resources.
                NativeMethods.StrongNameFreeBuffer(buffer);
            }

            return keyFileBuffer;
        }

        /// <summary>
        /// Adds the key file to the project.
        /// </summary>
        /// <param name="project">The project to configure.</param>
        private void AddKeyFileToProject(Project project)
        {
            // Save the key to a file. 
            if (this.keyBuffer != null)
            {
                string destinationDirectory = Path.GetDirectoryName(project.FullName);
                string keySavePath = Path.Combine(destinationDirectory, KeyFileName);

                File.WriteAllBytes(keySavePath, this.keyBuffer);
                project.ProjectItems.AddFromFile(keySavePath);

                // Add properties in the project to use the key for signing.
                EnvDTE.Properties projProps = project.Properties;
                projProps.Item("SignAssembly").Value = true;
                projProps.Item("AssemblyOriginatorKeyFile").Value = KeyFileName;
            }
        }

        /// <summary>
        /// Contains native methods.
        /// </summary>
        private static class NativeMethods
        {
            [DllImport("mscoree.dll")]
            internal static extern int StrongNameFreeBuffer(IntPtr pbMemory);

            [DllImport("mscoree.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
            internal static extern int StrongNameKeyGen(IntPtr wszKeyContainer, uint dwFlags, out IntPtr KeyBlob, out uint KeyBlobSize);

            [DllImport("mscoree.dll", CharSet = CharSet.Unicode)]
            internal static extern int StrongNameErrorInfo();
        }

        #endregion
    }
}
